package com.tao.common.utils;



import jakarta.mail.internet.MimeMessage;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import java.util.Optional;

public class MailUtil {

    private JavaMailSender javaMailSender;
    private MailProperties mailProperties;

    public MailUtil(JavaMailSender javaMailSender, MailProperties mailProperties) {
        this.javaMailSender = javaMailSender;
        this.mailProperties = mailProperties;
    }

    /**
     * @param to 收件人
     * @param subject 主题
     * @param content 正文
     */
    public void send(String to, String subject, String content) throws Exception{
        // 创建一个邮件信息
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 使用 MimeMessageHelper 辅助设置邮件信息
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false);

        // 从配置文件中获取
        String personal = Optional.ofNullable(mailProperties.getProperties().get("personal")) // 通过配置文件获取发件人名称
                .orElse(mailProperties.getUsername()); // 如果 personal 为空就获取 username (发件人邮箱)
        // 发件人和发件人名称
        helper.setFrom(mailProperties.getUsername(), personal);
        helper.setTo(to); // 接收方
        helper.setSubject(subject); // 邮件的主题
        helper.setText(content, true); // 正文

        javaMailSender.send(mimeMessage);
    }
}
